<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-pic"></i> 动态管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <el-input v-model="searchForm.authorId" placeholder="作者ID" class="handle-input mr10 mb10" clearable />
        <el-input v-model="searchForm.authorName" placeholder="作者名字" class="handle-input mr10 mb10" clearable />
        <el-input v-model="searchForm.noteTitle" placeholder="笔记标题" class="handle-input mr10" clearable />
        <el-input v-model="searchForm.ipRealAddress" placeholder="IP真实地址" class="handle-input mr10" clearable />
        <el-select v-model="searchForm.noteCategory" placeholder="类型" class="handle-input mr10" clearable>
          <el-option label="普通发布" :value="0" />
          <el-option label="宠物日记" :value="1" />
          <el-option label="热点" :value="2" />
        </el-select>
        <!-- <el-date-picker v-model="searchForm.publishTime" type="datetimerange" range-separator="至"
          start-placeholder="开始时间" end-placeholder="结束时间" class="mr10" /> -->
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="showAddMoment">新增动态</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="momentTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="动态ID" />
        <el-table-column prop="city" label="动态所属城市" />
        <el-table-column prop="publisherAvatar" label="发布者头像" width="100">
          <template #default="scope">
            <el-image :src="scope.row.publisherAvatar" style="width:40px;height:40px;border-radius:50%;" />
          </template>
        </el-table-column>
        <el-table-column prop="publisherName" label="发布者昵称/ID">
          <template #default="scope">
            {{ scope.row.publisherName }} / {{ scope.row.publisherId }}
          </template>
        </el-table-column>
        <el-table-column prop="firstPicture" label="首图">
          <template #default="scope">
            <el-image v-if="scope.row.firstPicture" :src="scope.row.firstPicture" style="width:60px;height:60px;border-radius:4px;" fit="cover" :preview-src-list="[scope.row.firstPicture]" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="mediaList" label="图片/视频">
          <template #default="scope">
            <span v-if="scope.row.noteType === 3 || !scope.row.mediaList || scope.row.mediaList.length === 0">-</span>
            <el-button v-else type="primary" size="mini" @click="openMediaDialog(scope.row.mediaList)">
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="200">
          <template #default="scope">
            <span>{{ scope.row.title || '无标题' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" width="300">
          <template #default="scope">
            <div class="content-cell">
              {{ scope.row.content || '无内容' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="topicsList" label="话题">
          <template #default="scope">
            <div v-if="scope.row.topicsList && scope.row.topicsList.length > 0">
              <el-tag v-for="topic in scope.row.topicsList" :key="topic.topicsId" size="mini" class="topic-tag">
                {{ topic.topicName }}
              </el-tag>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="160">
          <template #default="scope">
            {{ dateFormat(scope.row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" align="center">
          <template #default="scope">
            <el-button type="text" @click="showEditMoment(scope.row)">编辑动态</el-button>
            <el-button type="text" @click="addComment(scope.row)">添加评论</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除动态</el-button>
            <el-button type="text" @click="viewComments(scope.row)">查看评论列表</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 媒体预览弹窗 -->
    <el-dialog v-model="mediaDialog.visible" width="40%" title="媒体预览" append-to-body>
      <div style="display: flex; justify-content: center;">
        <media-view v-if="mediaDialog.list.length" :list="mediaDialog.list" />
      </div>
    </el-dialog>



    <!-- 新建/编辑动态弹窗 -->
    <el-dialog v-model="addDialog.visible" :title="addDialog.isEdit ? '编辑动态' : '新增动态'" width="50%">
      <el-form :model="addDialog.form" label-width="120px">
        <el-form-item label="发布者" required>
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="publisherDisplayText" :key="publisherDisplayText" placeholder="请选择发布者" readonly style="flex: 1;" />
            <el-button @click="selectPublisher" :disabled="addDialog.form.noteCategory === 2">选择发布者</el-button>
            <el-button v-if="addDialog.form.publisher && addDialog.form.noteCategory !== 2" type="danger" @click="clearPublisher">清除</el-button>
          </div>
          <div v-if="addDialog.form.noteCategory === 2" class="form-tip">热点类型发布者固定为官方账号</div>
        </el-form-item>
        <el-form-item label="内容类型" required>
          <el-radio-group v-model="addDialog.form.noteType">
            <el-radio :label="1">图文</el-radio>
            <el-radio :label="2">视频</el-radio>
            <el-radio :label="3">文字</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布类型" required>
          <el-radio-group v-model="addDialog.form.noteCategory">
            <el-radio :label="0">发广场</el-radio>
            <el-radio :label="1">宠物日记</el-radio>
            <el-radio :label="2">热点</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="addDialog.form.noteCategory === 1" label="宠物ID" required>
          <el-input v-model="addDialog.form.petId" placeholder="请输入宠物ID" />
          <div class="form-tip">宠物日记类型必须选择宠物</div>
        </el-form-item>
        <el-form-item v-if="addDialog.form.noteType !== 3" label="首图" required>
          <MediaUploader v-model="addDialog.form.firstPictureList" :limit="1" accept-type="image" />
          <div class="form-tip">请上传一张首图作为动态封面</div>
        </el-form-item>
        <el-form-item v-if="addDialog.form.noteType !== 3" label="媒体文件" required>
          <MediaUploader v-model="addDialog.form.mediaList" :limit="addDialog.form.noteType === 1 ? 9 : 1" :accept-type="addDialog.form.noteType === 1 ? 'image' : 'video'" />
          <div class="form-tip">
            {{ addDialog.form.noteType === 1 ? '图文类型最多上传9张图片' : '视频类型只能上传1个视频' }}
          </div>
        </el-form-item>
        <el-form-item label="标题" required>
          <el-input v-model="addDialog.form.title" placeholder="标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input v-model="addDialog.form.content" type="textarea" :rows="4" placeholder="请输入动态内容" />
        </el-form-item>
        <el-form-item label="创建时间" required>
          <el-date-picker v-model="addDialog.form.createTime" type="datetime" placeholder="选择创建时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
          <div class="form-tip">设置动态的创建时间</div>
        </el-form-item>
        <!-- <el-form-item label="话题搜索">
          <el-input v-model="addDialog.form.noteTopics" placeholder="请输入话题搜索关键词" />
          <div class="form-tip">用于搜索相关话题的关键词</div>
        </el-form-item> -->
        <el-form-item label="话题">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input v-model="topicDisplayText" placeholder="选择话题（可选）" readonly style="flex: 1;" />
            <el-button @click="selectTopic">选择话题</el-button>
            <el-button v-if="addDialog.form.selectedTopics.length > 0" type="danger" @click="clearTopic">清除</el-button>
          </div>
          <div v-if="addDialog.form.selectedTopics.length > 0" class="selected-topics">
            <el-tag v-for="topic in addDialog.form.selectedTopics" :key="topic.topicId" closable @close="removeTopicTag(topic)" class="topic-tag">
              {{ topic.topicName }}
            </el-tag>
          </div>
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="addDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="addDialog.isEdit ? saveEdit() : saveAdd()">保存</el-button>
      </template>
    </el-dialog>

    <!-- 选择用户弹窗 -->
    <SelectUser v-model="selectUserVisible" :multiple="false" :selected-user-ids="addDialog.form.publisher ? [addDialog.form.publisher.userId] : []" @confirm="handleSelectUser" />

    <!-- 选择话题弹窗 -->
    <SelectTopic v-model="selectTopicVisible" :selected-data="addDialog.form.selectedTopics" @confirm="handleSelectTopic" />

    <!-- 添加评论弹窗 -->
    <el-dialog v-model="commentDialog.visible" title="添加评论" width="50%">
      <el-form :model="commentDialog.form" label-width="120px">
        <el-form-item label="选择动态" required>
          <el-input v-model="commentMomentDisplayText" placeholder="当前动态" readonly style="flex: 1;" />
          <div class="form-tip">当前行就是已经选中的动态，无需选择</div>
        </el-form-item>
        <el-form-item label="回复类型" required>
          <el-radio-group v-model="commentDialog.form.replayType">
            <el-radio :label="0">文字</el-radio>
            <el-radio :label="1">图片</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="commentDialog.form.replayType === 0" label="回复内容" required>
          <el-input v-model="commentDialog.form.replayContent" type="textarea" :rows="4" placeholder="请输入回复内容" />
        </el-form-item>
        <el-form-item v-if="commentDialog.form.replayType === 1" label="回复图片" required>
          <MediaUploader v-model="commentDialog.form.imageList" :limit="1" accept-type="image" />
          <div class="form-tip">请上传一张图片</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="commentDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveComment">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import MediaUploader from "@/components/mediaUploader.vue";
import MediaView from "@/components/mediaVIew.vue";
import SelectUser from "@/components/selectUser.vue";
import SelectTopic from "@/components/selectTopic.vue";
import { getMoments, addMoments, deleteMoments, updateMoments, addBlogReply } from "@/api/content";
import { getIp } from "@/utils/index.js";

export default {
  name: "MomentsManagement",
  components: {
    MediaView,
    MediaUploader,
    SelectUser,
    SelectTopic
  },
  data() {
    return {
      searchForm: {
        authorId: "",
        authorName: "",
        noteTitle: "",
        ipRealAddress: "",
        noteCategory: "",
        publishTime: [],
      },
      tableData: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      mediaDialog: {
        visible: false,
        list: [],
      },

      addDialog: {
        visible: false,
        isEdit: false, // 是否为编辑模式
        editId: null, // 编辑的动态ID
        form: {
          noteType: 1, // 默认图文类型
          noteCategory: 0, // 默认发广场
          petId: "", // 宠物ID
          firstPictureList: [], // 首图列表
          mediaList: [],
          title: "",
          content: "",

          noteTopics: "", // 话题搜索字段
          createTime: "", // 创建时间
          publisher: null, // 选中的发布者
          selectedTopics: [], // 选中的话题列表
        },
      },
      // 用户选择弹窗
      selectUserVisible: false,
      // 话题选择弹窗
      selectTopicVisible: false,

      // 添加评论弹窗
      commentDialog: {
        visible: false,
        currentMoment: null, // 当前选中的动态
        form: {
          replayType: 0, // 回复类型：0文字，1图片
          replayContent: "", // 回复内容
          imageList: [], // 图片列表
        },
      },

    };
  },
  computed: {
    publisherDisplayText() {
      return this.addDialog.form.publisher ?
        `${this.addDialog.form.publisher.nickname} (${this.addDialog.form.publisher.userId})` :
        '';
    },
    topicDisplayText() {
      const count = this.addDialog.form.selectedTopics.length;
      if (count === 0) return '';
      if (count === 1) return this.addDialog.form.selectedTopics[0].topicName;
      return `已选择 ${count} 个话题`;
    },
    // 添加评论弹窗中的动态显示文本
    commentMomentDisplayText() {
      return this.commentDialog.currentMoment ?
        `${this.commentDialog.currentMoment.title || '无标题'} (ID: ${this.commentDialog.currentMoment.id})` :
        '';
    }
  },
  mounted() {
    // 检查路由参数中是否有userId，如果有就赋值给authorId作为默认搜索参数
    if (this.$route.query.userId) {
      this.searchForm.authorId = this.$route.query.userId;
    }
    this.getData();
  },
  watch: {
    'addDialog.form.noteType'(newType, oldType) {
      if (newType !== oldType) {
        // 切换类型时清空媒体文件
        this.addDialog.form.mediaList = [];
        this.addDialog.form.firstPictureList = [];
      }
    },
    'addDialog.form.noteCategory'(newCategory, oldCategory) {
      if (newCategory !== oldCategory) {
        if (newCategory !== 1) {
          // 切换到非宠物日记时清空宠物ID
          this.addDialog.form.petId = '';
        }

        // 当切换为热点类型时，发布人写死为官方
        if (newCategory === 2) {
          this.addDialog.form.publisher = {
            userId: '0f56366a8054fe012b04ed9b2e3d1201',
            nickname: '铂时官方',
            userPic: '' // 头像可能需要设置，这里暂时留空
          };
        }
        // 当从热点类型切换到其他类型时，清除官方账号
        else if (oldCategory === 2) {
          this.addDialog.form.publisher = null;
        }
      }
    },
    'commentDialog.form.replayType'() {
      // 切换评论类型时清空内容
      this.commentDialog.form.replayContent = '';
      this.commentDialog.form.imageList = [];
    },
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    formatDateTime(date) {
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },

    handleSearch() {
      // 搜索时重置到第一页
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        // 必须的分页参数
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      // 根据搜索表单构建查询参数
      if (this.searchForm.authorId) {
        params.authorId = this.searchForm.authorId;
      }
      if (this.searchForm.authorName) {
        params.authorName = this.searchForm.authorName;
      }
      if (this.searchForm.noteTitle) {
        params.noteTitle = this.searchForm.noteTitle;
      }
      if (this.searchForm.ipRealAddress) {
        params.ipRealAddress = this.searchForm.ipRealAddress;
      }
      if (this.searchForm.noteCategory !== "" && this.searchForm.noteCategory !== null) {
        params.noteCategory = this.searchForm.noteCategory;
      }
      if (this.searchForm.publishTime && this.searchForm.publishTime.length === 2) {
        params.startTime = this.searchForm.publishTime[0];
        params.endTime = this.searchForm.publishTime[1];
      }

      return params;
    },
    buildMediaList(item) {
      const mediaList = [];

      // 根据noteType处理不同类型的媒体，排除首图
      switch (item.noteType) {
        case 1: // 图文类型 - 只获取imgList字段
          if (item.imgList && item.imgList.length > 0) {
            item.imgList.forEach(img => {
              // 排除首图
              if (img !== item.firstPicture) {
                mediaList.push({
                  type: 'image',
                  url: img
                });
              }
            });
          }
          break;

        case 2: // 视频类型 - 只获取videoUrl字段
          if (item.videoUrl) {
            mediaList.push({
              type: 'video',
              url: item.videoUrl
            });
          }
          break;

        case 3: // 文字类型 - 不处理任何媒体
          break;
      }

      return mediaList;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getMoments(params);

        if (response && response.data) {
          // 将API返回的数据映射到表格需要的格式
          this.tableData = response.data.rows.map(item => ({
            id: item.noteId || item.id,
            city: item.ipRealAddress || '未知',
            publisherAvatar: item.authorAvatar || item.avatarUrl || '',
            publisherName: item.authorName || '',
            publisherId: item.authorId || '',
            noteType: item.noteType,
            firstPicture: item.firstPicture,
            mediaList: this.buildMediaList(item),
            title: item.noteTitle,
            content: item.noteContent,
            topic: item.noteLabel,
            topicsList: item.topicsList || [], // 话题列表数据
            publishTime: item.createTime,
            // 保留原始数据用于编辑
            _original: item
          }));

          // 更新总数（如果接口返回了总数）
          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取动态数据失败:', error);
        this.$message.error('获取动态数据失败');
      }
    },
    openMediaDialog(list) {
      this.mediaDialog.list = list || [];
      this.mediaDialog.visible = true;
    },
    async saveEdit() {
      try {
        // 验证必填项
        if (!this.addDialog.form.publisher) {
          this.$message.error('请选择发布者');
          return;
        }
        if (!this.addDialog.form.title.trim()) {
          this.$message.error('请输入标题');
          return;
        }
        if (!this.addDialog.form.content.trim()) {
          this.$message.error('请输入动态内容');
          return;
        }
        // 验证媒体文件（非文字类型需要媒体文件）
        if (this.addDialog.form.noteType !== 3) {
          if (!this.addDialog.form.mediaList || this.addDialog.form.mediaList.length === 0) {
            this.$message.error('请上传媒体文件');
            return;
          }
        }

        // 构建编辑参数，复用新增的参数构建逻辑
        const params = await this.buildAddParams();
        // 添加ID用于编辑
        params.id = this.addDialog.editId;
        params.noteId = this.addDialog.editId; // 确保ID字段正确

        // 构建updateDTO参数
        const updateDTO = params;

        await updateMoments(updateDTO);

        this.$message.success('编辑动态成功');
        this.addDialog.visible = false;
        this.getData();
      } catch (error) {
        console.error('编辑动态失败:', error);
        this.$message.error('编辑动态失败');
      }
    },
    handleDelete(row) {
      this.$confirm("确定要删除该动态吗？", "提示", { type: "warning" }).then(async () => {
        try {
          // 构建删除参数
          const delDTO = {
            id: row.id
          };

          await deleteMoments(delDTO);

          this.$message.success('删除动态成功');
          this.getData();
        } catch (error) {
          console.error('删除动态失败:', error);
          this.$message.error('删除动态失败');
        }
      }).catch(() => {
        // 用户取消删除
      });
    },
    viewComments(row) {
      // 跳转到评论列表页面，带上noteId参数
      this.$router.push({
        path: '/blogReply',
        query: {
          noteId: row.id
        }
      });
    },
    addComment(row) {
      // 显示添加评论弹窗
      this.commentDialog.visible = true;
      this.commentDialog.currentMoment = row;
      this.commentDialog.form = {
        replayType: 0,
        replayContent: "",
        imageList: [],
      };
    },
    showAddMoment() {
      this.addDialog.visible = true;
      this.addDialog.isEdit = false;
      this.addDialog.editId = null;
      this.addDialog.form = {
        noteType: 1, // 默认图文类型
        noteCategory: 0, // 默认发广场
        petId: "", // 宠物ID
        firstPictureList: [], // 首图列表
        mediaList: [],
        title: "",
        content: "",
        topic: "",
        noteTopics: "", // 话题搜索字段
        createTime: this.formatDateTime(new Date()), // 新增时默认当前时间
        publisher: null,
        selectedTopics: [],
      };
    },
    async showEditMoment(row) {
      console.log('编辑动态 - row数据:', row);
      console.log('编辑动态 - original数据:', row._original);

      this.addDialog.isEdit = true;
      this.addDialog.editId = row.id;

      // 填充编辑数据
      const original = row._original;
      const noteCategory = parseInt(original.noteCategory) || 0;

      // 如果是热点类型，发布人固定为官方账号
      const publisher = noteCategory === 2 ?
        {
          userId: '0f56366a8054fe012b04ed9b2e3d1201',
          nickname: '铂时官方',
          userPic: ''
        } :
        {
          userId: row.publisherId || original.authorId,
          nickname: row.publisherName || original.authorName,
          userPic: row.publisherAvatar || original.authorAvatar || ''
        };

      // 先重置表单数据
      this.addDialog.form = {
        noteType: original.noteType || 1,
        noteCategory: noteCategory,
        petId: original.petId || "",
        firstPictureList: [],
        mediaList: [],
        title: row.title || "",
        content: row.content || "",
        noteTopics: "", // 编辑时先留空，按照要求不做赋值
        createTime: row.publishTime ? this.formatDateTime(new Date(row.publishTime)) : this.formatDateTime(new Date()), // 编辑时赋值列表返回的创建时间
        selectedTopics: this.formatTopicsForEdit(row.topicsList), // 编辑时赋值话题列表
        publisher: publisher
      };

      // 等待下一个tick，确保表单重置完成
      await this.$nextTick();

      // 然后设置媒体数据
      this.addDialog.form.firstPictureList = original.firstPicture ? [{
        url: original.firstPicture,
        type: 'image/jpeg',
        name: 'firstPicture.jpg'
      }] : [];

      this.addDialog.form.mediaList = this.buildEditMediaList(original);

      console.log("editRow", this.addDialog);

      // 再等待一个tick，确保媒体数据设置完成
      await this.$nextTick();

      // 最后显示弹窗
      this.addDialog.visible = true;
    },
    buildEditMediaList(original) {
      const mediaList = [];

      // 根据类型构建媒体列表
      if (original.noteType === 1 && original.imgList) {
        // 图文类型，排除首图
        original.imgList.forEach((img, index) => {
          if (img !== original.firstPicture) {
            mediaList.push({
              url: img,
              type: 'image/jpeg',
              name: `image_${index}.jpg`
            });
          }
        });
      } else if (original.noteType === 2 && original.videoUrl) {
        // 视频类型
        mediaList.push({
          url: original.videoUrl,
          type: 'video/mp4',
          name: 'video.mp4'
        });
      }

      return mediaList;
    },
    async saveAdd() {
      try {
        // 验证必填项
        if (!this.addDialog.form.publisher) {
          this.$message.error('请选择发布者');
          return;
        }
        if (!this.addDialog.form.title.trim()) {
          this.$message.error('请输入标题');
          return;
        }
        if (!this.addDialog.form.content.trim()) {
          this.$message.error('请输入动态内容');
          return;
        }
        // 验证媒体文件（非文字类型需要媒体文件）
        if (this.addDialog.form.noteType !== 3) {
          if (!this.addDialog.form.mediaList || this.addDialog.form.mediaList.length === 0) {
            this.$message.error('请上传媒体文件');
            return;
          }
        }

        // /hi构建新增动态的参数
        const params = await this.buildAddParams();

        await addMoments(params);

        this.$message.success('新增动态成功');
        this.addDialog.visible = false;
        this.getData();
      } catch (error) {
        console.error('新增动态失败:', error);
        this.$message.error('新增动态失败');
      }
    },
    async buildAddParams() {
      const form = this.addDialog.form;

      // 处理首图
      let firstPicture = '';
      let firstPictureWidth = 0;
      let firstPictureHeight = 0;

      if (form.firstPictureList && form.firstPictureList.length > 0) {
        firstPicture = form.firstPictureList[0].url;
        // 这里可以获取图片尺寸，暂时设为默认值
        firstPictureWidth = 800;
        firstPictureHeight = 600;
      }

      // 处理媒体文件
      const imgs = [];
      let videoUrl = '';

      if (form.mediaList && form.mediaList.length > 0) {
        form.mediaList.forEach(media => {
          if (media.type && media.type.startsWith('image/')) {
            imgs.push(media.url);
          } else if (media.type && media.type.startsWith('video/')) {
            videoUrl = media.url;
          }
        });
      }

      // 根据接口文档构建参数
      // 根据noteCategory获取分类名称
      const getCategoryName = (category) => {
        switch (category) {
          case 0: return "发广场";
          case 1: return "宠物日记";
          case 2: return "热点";
          default: return "发广场";
        }
      };

      return {
        // 发布者信息
        authorId: form.publisher?.userId || "",
        authorName: form.publisher?.nickname || "",
        noteCategory: form.noteCategory.toString(),
        noteCategoryName: getCategoryName(form.noteCategory),

        // 用户输入的参数
        noteTitle: form.title || '',
        noteContent: form.content || '',
        noteType: form.noteType,

        // 媒体相关
        imgs: imgs,
        firstPicture: firstPicture,
        firstPictureWidth: firstPictureWidth,
        firstPictureHeight: firstPictureHeight,
        videoUrl: videoUrl,

        // 话题相关
        noteLabel: '',
        // 根据API文档，需要传递话题列表
        topics: form.selectedTopics.map(topic => ({
          topicsId: topic.topicId,
          topicName: topic.topicName
        })),

        // IP地址相关
        ipAddress: getIp(),
        // ipAddress: "122.231.110.130", // 先写死
        // musicUrl: '',
        // noteStatus: 0,
        petId: form.noteCategory === 1 ? parseInt(form.petId) || "" : "",
        // deleted: 0,
        // version: 0,
        createTime: form.createTime || this.formatDateTime(new Date()),
        // updateTime: this.formatDateTime(new Date())
      };
    },
    selectPublisher() {
      // 如果是热点类型，不允许选择发布者
      if (this.addDialog.form.noteCategory === 2) {
        this.$message.info('热点类型发布者固定为官方账号');
        return;
      }
      this.selectUserVisible = true;
    },
    clearPublisher() {
      // 如果是热点类型，不允许清除发布者
      if (this.addDialog.form.noteCategory === 2) {
        this.$message.info('热点类型发布者固定为官方账号');
        return;
      }
      this.addDialog.form.publisher = null;
    },
    handleSelectUser(selectedUsers) {
      if (selectedUsers && selectedUsers.length > 0) {
        this.addDialog.form.publisher = selectedUsers[0];
      }
    },
    selectTopic() {
      this.selectTopicVisible = true;
    },
    clearTopic() {
      this.addDialog.form.selectedTopics = [];
    },
    handleSelectTopic(selectedTopics) {
      this.addDialog.form.selectedTopics = selectedTopics;
    },
    removeTopicTag(topicToRemove) {
      this.addDialog.form.selectedTopics = this.addDialog.form.selectedTopics.filter(
        topic => topic.topicId !== topicToRemove.topicId
      );
    },

    // 上传相关方法
    handleUploadPreview(file) {
      // 预览上传的图片或视频
      window.open(file.url);
    },
    handleUploadRemove(file, fileList) {
      // 移除文件
      this.addDialog.form.mediaList = fileList;
    },
    beforeUpload(file) {
      // 可做类型/大小校验
      const isImage = file.type.startsWith('image/');
      const isVideo = file.type.startsWith('video/');
      if (!isImage && !isVideo) {
        this.$message.error('只能上传图片或视频文件');
        return false;
      }
      return true;
    },
    isVideo(file) {
      return file.type && file.type.startsWith('video/');
    },
    formatTopicsForEdit(topicsList) {
      // 将API返回的话题列表格式转换为编辑表单需要的格式
      if (!topicsList || !Array.isArray(topicsList)) {
        return [];
      }
      return topicsList.map(topic => ({
        topicId: topic.topicsId,
        topicName: topic.topicName
      }));
    },

    // 保存评论
    async saveComment() {
      try {
        // 验证必填项
        if (this.commentDialog.form.replayType === 0 && !this.commentDialog.form.replayContent.trim()) {
          this.$message.error('请输入回复内容');
          return;
        }
        if (this.commentDialog.form.replayType === 1 && (!this.commentDialog.form.imageList || this.commentDialog.form.imageList.length === 0)) {
          this.$message.error('请上传回复图片');
          return;
        }

        // 构建评论参数
        const params = {
          noteId: this.commentDialog.currentMoment.id,
          noteTitle: this.commentDialog.currentMoment.title || '无标题',
          replayType: this.commentDialog.form.replayType,
          replayContent: this.commentDialog.form.replayType === 0 ? this.commentDialog.form.replayContent : '',
          replayImgUrl: this.commentDialog.form.replayType === 1 && this.commentDialog.form.imageList.length > 0 ? this.commentDialog.form.imageList[0].url : '',
          replayStatus: 0, // 正常状态
          upCount: 0,
          parentId: '', // 顶级评论
          topParentId: '',
          createTime: this.formatDateTime(new Date()),
          ipAddress: getIp()
        };

        await addBlogReply(params);

        this.$message.success('添加评论成功');
        this.commentDialog.visible = false;
      } catch (error) {
        console.error('添加评论失败:', error);
        this.$message.error('添加评论失败');
      }
    },
  },
};
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  height: 60px;
  width: 60px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 148px;
  height: 148px;

  .pre-img {
    width: 146px;
    height: 146px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
    object-fit: cover;
  }

  .crop-input {
    position: absolute;
    width: 148px;
    height: 148px;
    left: 0px;
    top: 0px;
    opacity: 0;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
}

.picPreview {
  width: 100%;
}

.mb10 {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.content-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}

.selected-topics {
  margin-top: 8px;
}

.topic-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}
</style>
